package com.googlecode.stemwijzer.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.stemwijzer.client.StemwijzerService;
import com.googlecode.stemwijzer.shared.NameValidator;
import com.googlecode.stemwijzer.shared.model.IsAnswer;
import com.googlecode.stemwijzer.shared.model.IsQuestion;
import com.googlecode.stemwijzer.shared.model.IsQuestionnaireResult;
import com.googlecode.stemwijzer.shared.model.impl.QuestionnaireResult;

/**
 * Class GwtRpcStemwijzerService, this is the GWT-RPC implementation of the
 * StemwijzerService interface.
 * 
 * @author j.brosens
 */
@SuppressWarnings("serial")
public class GwtRpcStemwijzerService extends RemoteServiceServlet implements
		StemwijzerService {

	private IsQuestionnaireResult result = null;
	private String userName = null;

	@Override
	public IsQuestionnaireResult getResult() {
		if (this.result == null) {
			return null;
		}
		return this.result;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see com.googlecode.stemwijzer.client.StemwijzerService#registerUser(java.lang.String)
	 */
	@Override
	public Boolean registerUser(final String userName) {
		if (!NameValidator.isValid(userName)) {
			return false;
		}
		this.userName = userName;
		this.result = new QuestionnaireResult(userName, null);

		this.sleep(500);

		return true;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see com.googlecode.stemwijzer.client.StemwijzerService#resetSession()
	 */
	@Override
	public Boolean resetSession() {
		if (this.userName == null) {
			return false;
		}
		this.result = new QuestionnaireResult(userName, null);

		this.sleep(500);

		return true;
	}

	@Override
	public Boolean sendAnswer(IsQuestion question, IsAnswer answer) {
		if (this.result == null) {
			return false;
		}
		if ((question == null) || (answer == null)) {
			return false;
		}

		this.result.setAnswer(question, answer);

		this.sleep(500);

		return true;
	}

	/**
	 * Method adds a delay to the execution of the calling thread for the number
	 * of miliseconds specified.
	 * 
	 * @param milliseconds
	 *            Duration of the delay.
	 */
	private void sleep(final int milliseconds) {
		try {
			System.out.println("Zzz...");

			Thread.sleep(milliseconds);
		} catch (InterruptedException e) {
		}
	}
}
